<template>
  <el-upload
    ref="upload"
    class="file-upload"
    style="display: inline-block; margin-left: 10px;"
    :multiple="multiple"
    :disabled="!!percent"
    :action="action"
    :headers="headers"
    :before-upload="beforeUpload"
    :on-progress="uploadProgress"
    :on-error="uploadError"
    :on-success="uploadSuccess"
    :show-file-list="false">
    <el-button
      :size="buttonSize"
      type="primary"
      :loading="!!percent">{{ !!percent ? `${percent}%` : operationText }}</el-button>
  </el-upload>
</template>
<script>
import { getToken } from '@/utils/auth'
export default {
  name: 'Upload',
  props: {
    url: {
      type: String,
      default: '/dfile/file/upload'
    },
    buttonSize: {
      type: String,
      default: 'small'
    },
    multiple: {
      type: Boolean,
      default: false
    },
    operationText: {
      type: String,
      default: '浏览'
    }
  },
  data() {
    return {
      percent: 0,
      action: process.env.VUE_APP_BASE_API + this.url,
      headers: {
        Authorization: 'Bearer ' + getToken()
      }
    }
  },
  methods: {
    beforeUpload(file) {
      const size = file.size / 1024 / 1024 < 20
      // 限制图片大小
      if (!size) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
        return
      }
      return size
    },
    uploadProgress(e, file) {
      this.percent = parseInt(e.percent)
      if (e.percent === 100) {
        setTimeout(() => {
          this.percent = 0
        }, 800)
      }
    },
    uploadSuccess(response, file) {
      if (response.status === 200) {
        this.$emit('on-success', response, file)
        this.notifiySuccess('上传成功')
      } else {
        this.uploadError()
      }
    },
    uploadError() {
      this.percent = 0
      this.notifiyError('上传失败')
    },
    uploadAbort() {
      this.$refs.upload.abort()
      this.percent = 0
    }
  }
}
</script>
